package ui.panel.showroom;

import cerebrum.common.EmptyChecker;
import cerebrum.cache.ImagesDataLoaderCache;
import cerebrum.common.LunarUtil;
import ui.factory.SingletonFactory;
import cerebrum.controller.screen.VerseUtil;
import cerebrum.entity.FontCacheEntity;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.TilePane;
import javafx.scene.text.Text;
import javafx.stage.StageStyle;
import ui.task.ScreenSaverTask;
import ui.util.CommonUtil;
import ui.util.Window;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Timer;

public class ScreenSaverStage extends Window {
    private final double height = CommonUtil.getSystemHeight() + 100;
    private double systemWidth = CommonUtil.getSystemWidth();
    private LocalDateTime localDateTime = LocalDateTime.now();
    private static ScreenSaverStage instance = null;

    //调用单例工厂
    public static ScreenSaverStage getInstance() {
        if (instance == null) {
            instance = SingletonFactory.getWeakInstace(ScreenSaverStage.class);
        }
        return instance;
    }

    public ScreenSaverStage() throws IOException {
        URL resource = getClass().getResource("/fxml/ScreenSaver.fxml");
        root = FXMLLoader.load(resource);

        Scene scene = new Scene(root, -systemWidth, height);
//        scene.setFill(Paint.valueOf("#ffffff00"));
        initStyle(StageStyle.TRANSPARENT);
        setScene(scene);
        setTitle("IceoLogy壁纸");
        //设置页面始终最靠前
        this.setAlwaysOnTop(true);
        calendarStyleSetting();

    }

    //电子时钟pane的样式
    private void spiritStyle() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String strDate = dtf.format(localDateTime);
        //获取当天的
        HashMap<String, Object> today = LunarUtil.today();

        StringBuilder sb = new StringBuilder();
        //2020/03/22     辛丑年二月初九     星期天
        sb.append(strDate).append("     ").append(today.get("lunarYear")).append("（")
                .append(today.get("lunarDizhi")).append("）").append("年").append(today.get("lunarMonth"))
                .append("月").append(today.get("lunarDay")).append("     ").append(today.get("week"));

        ((Label) $("spirit_msg")).setText(sb.toString());
        String todayMsg = getTodayMsg(today);//节日及命名日
        ((Label) $("spirit_namingDay")).setText(todayMsg);
    }

    /**
     * 整体样式及图片设定
     */
    public void screenSaverStyleSetting() {
        ((Pane) $("screenSaver")).setPrefWidth(systemWidth);
        ((Pane) $("screenSaver")).setPrefHeight(height);
        //缩放图片到指定尺寸
        ((ImageView) $("screenSaver-image")).setFitWidth(systemWidth);
        ((ImageView) $("screenSaver-image")).setFitHeight(height);
        ((ImageView) $("screenSaver-image")).setImage(new Image(ImagesDataLoaderCache.next()));

    }

    //诗词的样式设定
    public void verseStyle() {
        List<String> list = getVerse();
        String verse = list.get(0);
        String author = list.get(1);
        if (verse.length() > 17) {
            String[] split = verse.split("[，；。！]");
            String msg = "";
            String spare = "";
            int length = split.length;
            if (length < 3) {//三句
                ((Text) $("verse_msg")).setText(verse);
                Text verseAuthor = ((Text) $("verse_author"));
                verseAuthor.setText(author);
                verseAuthor.setLayoutX(125.0);
            } else if (length ==3){
                msg = split[0] + ",";
                spare = split[1] + "," + split[2] + "。";
            }else {//大于三句
                for (int i = 0; i < length; i++) {
                    if (i < length / 2) {
                        msg += split[i] + ",";
                    } else if (i == length - 1) {
                        spare += split[i];
                    } else {
                        spare = split[i] + ",";

                    }
                }
                spare += "。";

            }

            ((Text) $("verse_msg")).setText(msg);
            Text verseSpare = ((Text) $("verse_spare"));
            verseSpare.setVisible(true);
            verseSpare.setText(spare);
            Text verseAuthor = ((Text) $("verse_author"));
            verseAuthor.setText(author);
            verseAuthor.setLayoutX(180);
        } else {
            ((Text) $("verse_msg")).setText(verse);
            Text verseAuthor = ((Text) $("verse_author"));
            verseAuthor.setText(author);
            verseAuthor.setLayoutX(125.0);
        }
        ((Text) $("verse_msg")).setFont(FontCacheEntity.YGY2TTF);
        ((Text) $("verse_spare")).setFont(FontCacheEntity.YGY2TTF);
        ((Text) $("verse_author")).setFont(FontCacheEntity.liguofuTTF);
    }
    //清除诗词
    public void verseClean() {
        ((Text) $("verse_msg")).setText("");
        ((Text) $("verse_spare")).setText("");
        ((Text) $("verse_author")).setText("");
    }
    //获取诗词
    private List<String> getVerse() {
        List<String> list = VerseUtil.nextVerse();
        System.out.println(list);
        if (list.get(0).length() >= 30) {
            list = getVerse();
        }
        return list;
    }

    /**
     * 控制时间和日历随机出现
     */
    public void randomStyle() {
        Random random = new Random();
        int i = random.nextInt(10);
        if (i % 2 == 0) {
            ((Pane) $("spirit")).setVisible(true);
            ((Pane) $("calendar")).setVisible(false);
            spiritStyle();
        } else {
            ((Pane) $("spirit")).setVisible(false);
            ((Pane) $("calendar")).setVisible(true);
        }
    }

    /**
     * 电子时钟的定时任务
     */
    public void startTimer() {
        Timer timer = new Timer();
        int interval = 500;
        timer.schedule(new ScreenSaverTask(getInstance()), interval, interval);
    }

    /**
     * 日历pane整体样式设定
     */
    private void calendarStyleSetting() {
        //日历
        calendarStyle();
        //日历上方的月
        calendarMonthStyleSetting();
        //星期样式
        setWeeksFont();
    }

    /**
     * 日历样式及逻辑设定
     *
     * @throws IOException
     */
    private void calendarStyle() {
        //获取本月最后一天时间
        LocalDateTime lastDay = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
        //获取本月最后一天天数
        int dayOfMonth = lastDay.getDayOfMonth();
        //获取月的第一天
        LocalDateTime firstDay = localDateTime.with(TemporalAdjusters.firstDayOfMonth());
        //第一天是周几
        int weekNum = firstDay.getDayOfWeek().getValue();
        for (int i = 1; i < weekNum; i++) {
            Text label = new Text("   ");
            label.setFont(FontCacheEntity.myFontTTF);
            ((TilePane) $("calendar_num")).getChildren().add(label);
        }
        for (int i = 1; i <= dayOfMonth; i++) {
            String lunarData = getMonthMaps(localDateTime, i);
            Text label = new Text(lunarData);
            if (i == localDateTime.getDayOfMonth()) {
                label.setFont(FontCacheEntity.FZBangSXJW);
            } else {
                label.setFont(FontCacheEntity.myFontTTF);
            }

            ((TilePane) $("calendar_num")).getChildren().add(label);
        }
        ((TilePane) $("calendar_num")).setPrefTileHeight((40));
        ((TilePane) $("calendar_num")).setPrefTileWidth(37);

    }

    /**
     * 日历上方的文字控制
     */
    private void calendarMonthStyleSetting() {

        String todayMsg = getTodayMsg(null);

        //拿到命名日元素
        Label namingDayLable = ((Label) $("calendar_namingDay"));
        namingDayLable.setText(todayMsg);
        namingDayLable.setFont(FontCacheEntity.yzxsTTF);
        namingDayLable.setPadding(new Insets(20));
        namingDayLable.setLayoutX(namingStyleDayPixelsCalculate(todayMsg));

        //------------------------- 月------------------------------------
        int month = localDateTime.getMonth().getValue();
        Label calendarMonthMsgLable = ((Label) $("calendar_month_msg"));
        calendarMonthMsgLable.setText(month + "月");
        calendarMonthMsgLable.setFont(FontCacheEntity.threeTTF56);
        //计算像素点
        int pixelsNum = calendarMonthStylePixelsCalculate(todayMsg);
        ((Label) $("calendar_month_msg")).setLayoutX(pixelsNum);
    }

    /**
     * 日历上方的月文字像素点计算
     *
     * @return
     */
    private int calendarMonthStylePixelsCalculate(String todayMsg) {
        int num = 355;
        long length = todayMsg.length();
        if (EmptyChecker.isEmpty(todayMsg) || length < 6) {
            num = 300;
        } else if (length > 5 && length < 10) {
            num = 286;
        }
        return num;
    }

    /**
     * 日历上方的命名日及节气像素点计算
     *
     * @param todayMsg
     * @return
     */
    private int namingStyleDayPixelsCalculate(String todayMsg) {
        int num = 0;
        long length = todayMsg.length();
        if (EmptyChecker.isEmpty(todayMsg) || length < 6) {
            num = 30;
        } else if (length > 5 && length < 10) {
            num = 20;
        }
        return num;
    }

    /**
     * 获取今天的命名日信息和节气信息等
     */
    private String getTodayMsg(HashMap<String, Object> todayMsg) {
        if (EmptyChecker.isEmpty(todayMsg)) {
            todayMsg = LunarUtil.today();
        }

        Object solarTerm = todayMsg.get("solarTerm");//节气
        Object holiday = todayMsg.get("holiday");//命名日
        Object lunarHoliday = todayMsg.get("lunarHoliday");//传统节日

        StringBuilder str = new StringBuilder();
        if (EmptyChecker.notEmpty(solarTerm)) {
            str.append(solarTerm);
        }
        if (EmptyChecker.notEmpty(lunarHoliday)) {
            msgCheck(str.toString());
            str.append(lunarHoliday);
        }
        if (EmptyChecker.notEmpty(holiday)) {
            msgCheck(str.toString());
            str.append(holiday);
        }
        return str.toString();
    }

    private void msgCheck(String str){
       str= (str.length() > 0?str+"/":str);
    }

    /**
     * 获取本月的农历及节气等
     */
    private String getMonthMaps(LocalDateTime localDate, int day) {
        HashMap<String, Object> hm = LunarUtil.oneDay(localDate.getYear(), localDate.getMonth().getValue(), day);
        String today = hm.get("today").toString();
        String lunarDay = hm.get("lunarDay").toString();
        Object solarTerm = hm.get("solarTerm");//节气
        Object holiday = hm.get("holiday");//命名日
        Object lunarHoliday = hm.get("lunarHoliday");//传统节日

        StringBuilder str = new StringBuilder();
        if (solarTerm != null) {
            str.append("\n ").append(solarTerm);
        }
        if (lunarHoliday != null) {
            str.append("\n ").append(lunarHoliday);
        }
        if (holiday != null) {
            str.append("\n ").append(holiday);
        }

        if (day == localDateTime.getDayOfMonth()) {
            if (str.length() > 0 && str.length() < 8) {
                return "   " + today + str;
            } else if (str.length() > 7) {
                return "   " + today + "  " + str;
            } else {
                return "  " + today + " \n" + lunarDay;
            }
        }
        if (str.length() > 0 && str.length() < 8) {
            return "    " + today + "\n" + str;
        } else if (str.length() > 7) {
            return "   " + today + str;
        } else {
            return "  " + today + "\n \n" + lunarDay;
        }
    }

    /**
     * 星期样式控制
     */
    private void setWeeksFont() {
        ((Text) $("weeks_one")).setFont(FontCacheEntity.threeTTF21);
        ((Text) $("weeks_two")).setFont(FontCacheEntity.threeTTF21);
        ((Text) $("weeks_three")).setFont(FontCacheEntity.threeTTF21);
        ((Text) $("weeks_four")).setFont(FontCacheEntity.threeTTF21);
        ((Text) $("weeks_five")).setFont(FontCacheEntity.threeTTF21);
        ((Text) $("weeks_six")).setFont(FontCacheEntity.threeTTF21);
        ((Text) $("weeks_seven")).setFont(FontCacheEntity.threeTTF21);
    }
}
